package com.zhengb.algorithmdemo.bytedance;

import com.zhengb.algorithmdemo.exam.linear.NumberUtil;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author zhengbo
 * @date 2020/3/14
 */
public class WeixinRedPacket {

    private final static int MIN_MONET = 1;

    /*模拟微信红包分发
     * @param totalMoney 总金额 单位分
     * @param personNum 总人数
     * @return 分发金额数组
     */
    public static double[] distributePacket(int totalMoney, int personNum) {
        if (totalMoney < MIN_MONET) {
            throw new IllegalArgumentException("总金额小于最小金额限制");
        }

        if (personNum <= 0) {
            throw new IllegalArgumentException("传入人数有误");
        }

        if (personNum == 1) {
            return new double[]{NumberUtil.div(totalMoney, 100)};
        }

        double[] result = new double[personNum];

        ThreadLocalRandom random = ThreadLocalRandom.current();

        int currentRemainMoney = totalMoney;

        int curRemainPerson = personNum;

        for (int i = 0; i < personNum; i++) {
            if (i == personNum - 1) {
                result[i] = NumberUtil.div(currentRemainMoney, 100);
            } else {
                int curRemainAverageMoney = currentRemainMoney / curRemainPerson;

                int money = random.nextInt(MIN_MONET, curRemainAverageMoney * 2);

                result[i] = NumberUtil.div(money, 100);

                currentRemainMoney = (currentRemainMoney - money);
                curRemainPerson--;
            }
        }

        return result;
    }

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i <= 100; i++) {
            new Thread(() -> {
                double[] result = distributePacket(1000, 9);

                System.out.println(Arrays.toString(result));

                double totalSum = 0;
                for (double v : result) {

                    if (v <= 0) {
                        throw new RuntimeException("不合法金额");
                    }
                    totalSum = NumberUtil.add(totalSum, v);
                }

                System.out.println(totalSum);

            }).start();
        }

        Thread.currentThread().join();
    }

}
